﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace Google_Music_Player
{
    public partial class gplayer : Form
    {
        public gplayer(string path)
        {
            if (path != string.Empty)
            {
                pathValue = path;
                loadArg = true;
            }
            InitializeComponent();

        }
        bool loadArg = false;
        string pathValue = string.Empty;
        int currentIndex = 0;
        private Timer next = new Timer();
        List<ListItem> songList = new List<ListItem>();
        const string TempFileName = "GMP_TEMP";
        bool dirty = false;

        void Document_Click(object sender, HtmlElementEventArgs e)
        {
            e.ReturnValue = false;
            HtmlDocument doc = sender as HtmlDocument;
            string html = string.Empty;
            if (doc.ActiveElement != null)
            {
                html = doc.ActiveElement.OuterHtml;

                if (html.StartsWith("<A") && html.IndexOf("popup.create") > -1)
                {
                    string smallname = doc.ActiveElement.OuterText;
                    string name = doc.ActiveElement.Parent.Parent.InnerText;
                    if (name.IndexOf(Environment.NewLine) > -1)
                        name = doc.ActiveElement.Parent.InnerText;
                    int timeDivide = name.IndexOf(":");
                    int timer = 1;
                    if (timeDivide > -1)
                    {
                        string time = name.Substring(timeDivide - 2, 2) + name.Substring(timeDivide, 3);
                         timer = ConvertStringToSpan(time);
                        //34
                    }

                    name = smallname.Trim();// +"\t" + time.Trim();

                    HtmlElement elm = e.FromElement;
                    //popup.create("http://new.saavn.com/popup/psong-6FQHIhsY.html",
                    int popupIndex = html.IndexOf("popup.create(\"") + 14;
                    int endIndex = html.IndexOf("\",", popupIndex);
                    html = html.Substring(popupIndex, endIndex - popupIndex).Replace("\\x3d", "=").Replace("\\x26", "&");
                    AddToList(name, html.Trim(), timer);
                }
                else
                {
                    e.ReturnValue = true;
                }
            }
        }
        
        private string LimitChars(string inputStr)
        {
            
            if (inputStr.Trim().Length > 25)
            {
                inputStr = inputStr.Trim().Substring(0, 25);
            }
            else if (inputStr.Trim().Length < 25)
            {
                inputStr = inputStr.Trim().PadRight(25);
            }
            return inputStr;
        }

        private void AddToList(string Name, string Value, int Timer)
        {
            if (PlayList.FindString(Name.Trim()) == -1)
            {
                PlayList.BeginUpdate();
                PlayList.Items.Add(new ListItem() { Name = Name, Value = Value, time = Timer});
                //PlayList.Items.Add(new ListItem(Name,Value,Timer));
                songList.Add(new ListItem() { Name = Name, Value = Value, time = Timer });
                PlayList.Refresh();
                PlayList.EndUpdate();
            }
        }

        private int ConvertStringToSpan(string time)
        {
            try
            {
                time = time.Trim();
                int mins = int.Parse(time.Substring(0, time.IndexOf(":")));
                int secs = int.Parse(time.Substring(time.IndexOf(":") + 1).Trim());
                return ((mins * 60) + secs + 2) * 1000;
            }
            catch
            {
                return 1;
            }
        }
        
        [Serializable()]
        public class ListItem 
        {
            public string Name;
            public string Value;
            public int time;
            public override string ToString()
            {
                return Name;
            }



        }
        
        private void wbgoogle_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (!dirty)
            {
                wbgoogle.Document.Click += new HtmlElementEventHandler(Document_Click);
                dirty = true;
            }
        }

        private void wbgoogle_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gplayer_Load(object sender, EventArgs e)
        {
                next.Tick += new EventHandler(next_Tick);
                SetSplitterWidth();
                LoadPlayList(true,pathValue);

        }

        void next_Tick(object sender, EventArgs e)
        {
            
            //if (PlayList.SelectedIndex < PlayList.Items.Count-1)
            if (currentIndex < PlayList.Items.Count - 1)
            {
                PlayList.SelectedIndex++;
                currentIndex = PlayList.SelectedIndex;
                btnPlay_Click(null, null);
            }
            else
            {
                next.Enabled = false;
                next.Stop();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            //btnStop_Click(null, null);
            
            int index = PlayList.SelectedIndex;
            if (index > -1)
            {
                PlayList.Items.RemoveAt(index);
                songList.RemoveAt(index);
            }
            if (index > currentIndex)
            {
                LocateSong();
            }
            else if (index < currentIndex)
            {
                currentIndex = currentIndex - 1;
                LocateSong();
            }
            else
            {
                btnStop_Click(null, null);
            }
            
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            currentIndex = PlayList.SelectedIndex;
            wbplayer.Url = new System.Uri("about:blank"); ;
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            currentIndex = PlayList.SelectedIndex;
            if (currentIndex > -1)
            {
                next.Interval = (PlayList.SelectedItem as ListItem).time;
                if (this.WindowState == FormWindowState.Minimized)
                    ShowNotification((PlayList.SelectedItem as ListItem).Name);
                next.Enabled = true;
                next.Start();
                Uri Url = new Uri((PlayList.SelectedItem as ListItem).Value);
                wbplayer.Navigate(Url, "_self", null, "Referrer: http://www.google.co.in/music");
                wbplayer.Focus();
                
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            btnStop_Click(null, null);
            PlayList.Items.Clear();
            songList.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SavePlayList(false);
        }

        private void SavePlayList(bool AutoSave)
        {
            if (!AutoSave)
            {
                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    sfd.Title = "Save Google Playlist";
                    sfd.AddExtension = true;
                    sfd.DefaultExt = "GMP";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            using (Stream stream = File.Open(sfd.FileName, FileMode.Create))
                            {
                                BinaryFormatter bin = new BinaryFormatter();
                                bin.Serialize(stream, songList);
                            }
                        }
                        catch (IOException)
                        {
                            MessageBox.Show("Error saving playlist");
                        }
                    }
                }
            }
            else
            {
                try
                {
                    string saveAt = Path.Combine(Path.GetTempPath(), TempFileName);
                    using (Stream stream = File.Open(saveAt, FileMode.Create))
                    {
                        BinaryFormatter bin = new BinaryFormatter();
                        bin.Serialize(stream, songList);
                    }
                }
                catch (IOException)
                {
                    MessageBox.Show("Error saving playlist");
                }
            }
        }

        private void LoadPlayList(bool AutoLoad, string customPath)
        {
            if (!AutoLoad)
            {
                PlayList.Items.Clear();
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.DefaultExt = "GMP";
                    ofd.Title = "Load Google playlist";
                    ofd.Multiselect = false;
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            using (Stream stream = File.Open(ofd.FileName, FileMode.Open))
                            {
                                BinaryFormatter bin = new BinaryFormatter();

                                songList = (List<ListItem>)bin.Deserialize(stream);
                                PlayList.Items.Clear();
                                foreach (ListItem item in songList)
                                {
                                    PlayList.Items.Add(item);
                                }
                            }
                        }
                        catch (IOException)
                        {
                            MessageBox.Show("Error loading playlist");
                        }
                    }
                }
            }
            else
            {
                string saveAt = string.Empty;
                if (loadArg)
                {
                    saveAt = pathValue;
                }
                else
                {
                    saveAt = Path.Combine(Path.GetTempPath(), TempFileName);
                }
                FileInfo fi = new FileInfo(saveAt);
                if (fi.Exists)
                {
                    try
                    {
                        using (Stream stream = File.Open(saveAt, FileMode.Open))
                        {
                            BinaryFormatter bin = new BinaryFormatter();

                            songList = (List<ListItem>)bin.Deserialize(stream);
                            PlayList.Items.Clear();
                            foreach (ListItem item in songList)
                            {
                                PlayList.Items.Add(item);
                            }
                        }
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Error loading playlist");
                    }
                }
            }
        }

        private void PlayList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            btnPlay_Click(null, null);
        }

        private void gplayer_ClientSizeChanged(object sender, EventArgs e)
        {
            wbgoogle.Refresh();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            LoadPlayList(false,"");
        }

        public Icon TextToIcon(string text, Font font, Color col)
        {
            Brush brush = new SolidBrush(col);
            Bitmap bitmap = new Bitmap(16, 16);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.DrawString(text, font, brush, 0, 0);
            IntPtr hIcon = bitmap.GetHicon();
           return Icon.FromHandle(hIcon);
        }

        private void gplayer_Resize(object sender, EventArgs e)
        {
            SetSplitterWidth();
            LocateSong();
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                ShowNotification((PlayList.SelectedItem as ListItem) == null ? "None" : (PlayList.SelectedItem as ListItem).Name);
            }
            else
            {
                GMPNotify.Visible = false;
            }
        }

        private void ShowNotification(string songName)
        {
            GMPNotify.Visible = true;
            GMPNotify.Text = songName;
            GMPNotify.BalloonTipText = "Now playing: " + songName;
            GMPNotify.ShowBalloonTip(5000);
            
        }

        private void gplayer_FormClosing(object sender, FormClosingEventArgs e)
        {
            GMPNotify.Visible = false;
            GMPNotify.Icon = null;
            GMPNotify.Visible = true;
            GMPNotify.Visible = false;
            SavePlayList(true);
        }

        private void PlayList_Leave(object sender, EventArgs e)
        {
           
            //HidePlayList();
        }

        private void LocateSong()
        {
            if (PlayList.Items.Count > 0)
                PlayList.SelectedIndex = currentIndex;
        }

        private void SetSplitterWidth()
        {
            if (this.WindowState != FormWindowState.Minimized)
            splitPanel.SplitterDistance = splitPanel.Panel1MinSize = this.Width - (panelDock.Width + 25);
           // HidePlayList();
        }

        private void ShowPlayList(bool show)
        {
           splitPanelWeb.Panel2Collapsed = splitPanel.Panel2Collapsed = !show;
            
                //splitPanel.SplitterDistance = this.Width + 15;
        }

        private void PlayList_MouseHover(object sender, EventArgs e)
        {
            splitPanel.SplitterDistance = splitPanel.Panel1MinSize;
        }

        private void btnCollapse_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Text == ">")
            {
                ShowPlayList(false);
                btnCollapse.Text = "<";
            }
            else
            {
                ShowPlayList(true);
                btnCollapse.Text = ">";
            }
        }

        private void GMPNotify_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Maximized;
            this.TopMost = true;
        }

        private void btnHome_Click(object sender, EventArgs e)
        {
            wbgoogle.Url = new System.Uri("http://www.google.co.in/music", System.UriKind.Absolute);
        }
    }

}
